package com.drcoffee.drcoffeemall.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.drcoffee.drcoffeemall.entry.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;


@Component
public class FileUploadDownloadUtils {

    // 文件上传路径
//    @Value("${img_path.initPath_B}")
    @Value("${nginx_file}")
    private String initPath;




    public static Result uploadFile2(MultipartFile file, String filepath, String fileName) throws IOException {
        Map<String, Object> resultMap = new HashMap<>();
        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();

        // 格式化时间戳为字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String formattedTimestamp = sdf.format(new Date(timestamp));
        // 图片文件名
        fileName = formattedTimestamp + "_" + fileName;
        int startIndex = filepath.indexOf("PartsMallFile");
        String filePath = filepath.substring(startIndex + "PartsMallFile".length());
        if (!file.isEmpty()) {
            try (BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream((filepath + File.separator + fileName)))) {
                out.write(file.getBytes());
                out.flush();
                return new Result(1, "SUCCESS", "Upload successfully", fileName);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return new Result(-1, "ERROR", "FileNotFoundException: " + e.getMessage(), fileName);

            } catch (IOException e) {
                e.printStackTrace();
                return new Result(-1, "ERROR", "IOException: " + e.getMessage(), fileName);
            }
        } else {
            return new Result(3, "SUCCESS", "The value of the file argument 'file' is null!", fileName);
        }
    }


    // 文件上传
    public static Map<String, Object> uploadFilea(MultipartFile file, String filepath, String fileName) throws IOException {
        Map<String, Object> resultMap = new HashMap<>();
        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();
        // 格式化时间戳为字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String formattedTimestamp = sdf.format(new Date(timestamp));
        // 图片文件名
        fileName = "image_" + formattedTimestamp + "_" + fileName;
        int lastIndexOf = fileName.lastIndexOf(".");
        String suffix = fileName.substring(lastIndexOf + 1);
        System.out.println(file);
        if (!file.isEmpty()) {
            if (suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase(".jpeg")) {
                BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
                int width = bufferedImage.getWidth() - 1;
                int height = bufferedImage.getHeight() - 1;
                int widthHeight = Math.max(width, height);
                width = widthHeight;
                height = widthHeight;
                Image image = bufferedImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
                //计算比例
                double ratio = 0; //缩放比例
                if ((bufferedImage.getHeight() > height) || (bufferedImage.getWidth() > width)) {
                    if (bufferedImage.getHeight() > bufferedImage.getWidth()) {
                        ratio = (double) height / bufferedImage.getHeight();
                    } else {
                        ratio = (double) width / bufferedImage.getWidth();
                    }
                    AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
                    image = op.filter(bufferedImage, null);
                }
                BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = scaledImage.createGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, width, height);
                if (width == image.getWidth(null))
                    g.drawImage(image, 0, (height - image.getHeight(null)) / 2, image.getWidth(null), image.getHeight(null), Color.white, null);
                else
                    g.drawImage(image, (width - image.getWidth(null)) / 2, 0, image.getWidth(null), image.getHeight(null), Color.white, null);
                g.dispose();
                // 将 BufferedImage 转为 File
                File outputFile = new File("C:\\Users\\zhoush\\Pictures\\tpm_part.png"); // 指定输出文件的名称和格式
                ImageIO.write(scaledImage, "jpg", outputFile);
                System.out.println("BufferedImage 已成功保存为文件: " + outputFile.getAbsolutePath());
            } else {
                resultMap.put("reason", "图片格式错误");
            }
        } else {
            resultMap.put("reason", "文件参数'file'的值为空！");
        }
        return resultMap;
    }


    // 获取当前系统路径
    private static String getUploadPath(String strPath) throws IOException {
        File file = new File(strPath);
        File fileParent = file.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        if (!file.exists()) file.mkdirs();
        return file.getAbsolutePath();
    }


// ...



    public Object downloadFile(String filePath) throws IOException {
        Map<String, Object> resultMap = new HashMap<>();
//        System.out.println(initPath + filePath);
//        File file = new File(initPath + filePath);
        System.out.println(filePath);
        File file = new File(filePath);
        if (file.exists()) {
            Path path = file.toPath();
            Resource resource = new UrlResource(path.toUri());
            String contentType = "application/octet-stream";
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(resource);
        } else {
            resultMap.put("result", false);
            resultMap.put("message", "下载失败，文件不存在！");
            return resultMap;
        }
    }

    /**
     * 删除指定文件
     */
    public static boolean deleteFile(String str) {
        System.out.println(str);
//        String str = "http://192.168.20.106:8082/file/image/home/explosion/领导者的十大修炼9.jpg";
        int index1 = str.indexOf("/"); // 获取第一个a的索引
        int index2 = str.indexOf("/", index1 + 2); // 获取第二个/的索引
        String Path = "";
        if (index2 != -1) {
            String result = str.substring(index2 + 1); // 从该字符后面的内容开始截取
            System.out.println(result.replaceAll("/", "\\\\"));
            Path = "C:\\Users\\zhoush\\Desktop\\Dr.coffee Mall File\\Dr.coffee-Mall\\src\\main\\resources\\static\\" + result.replaceAll("/", "\\\\");
        } else {
            System.out.println("字符串中没有足够的字符/");
        }
        System.out.println("----------------------------");
        System.out.println("Path:" + Path);
        File file = new File(Path);
        if (file.exists()) {
            // 删除指定文件
            Path filePath = Paths.get(Path);
            try {
                Files.delete(filePath);
                System.out.println("文件删除成功！");
                return true;
            } catch (IOException e) {
                System.out.println("文件删除失败：" + e.getMessage());
                return false;
            }
        } else {
            System.out.println("不存在");
            return true;
        }
    }

    //删除指定路径文件
    public static Object delFile(String url) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            String filePath = url;
            filePath = filePath.toString();
            java.io.File myDelFile = new java.io.File(filePath);
            if (!myDelFile.exists()) resultMap.put("result", true);
            myDelFile.delete();
            return resultMap.put("result", true);
        } catch (Exception e) {
            System.out.println("删除文件操作出错");
            e.printStackTrace();
            return resultMap.put("result", false);
        }
    }
}
